/*
 * pid.c
 *
 *  Created on: 2017年7月24日
 *      Author: Case
 */

#include "pid.h"

static	PID	sPID;
static	PID	*sptr = & sPID;

void	PID_Init(void)
{
	sptr->LastError 	= 0;
	sptr->PrevError 	= 0;
	sptr->SumError    = 0;
	sptr->Proportion 	= P_DATA;
	sptr->Integral 		= I_DATA;
	sptr->Derivative 	= D_DATA;
	sptr->SetPoint 		= 500;
}

//int	PID_Clac(int NextPoint)
//{
//	int 	iError,iIncpid,dError;b
//	iError 	= sptr->SetPoint - NextPoint;
//	dError  = iError - sptr->LastError;
//	sptr->SumError += iError;
//	iIncpid 	= sptr->Proportion*iError +            //P*当前误差
//				    sptr->Integral * sptr->SumError +		//I*总误差
//					sptr->Derivative * dError;		//D*微分量
//	sptr->PrevError = sptr->LastError;
//	sptr->LastError = iError;
//	iIncpid /= 1000;
//	return	iIncpid;
//}

//增量式PID控制设计
int IncPIDCalc(int NextPoint)
{
	 int iError, iIncpid;
	//当前误差
	iError = sptr->SetPoint - NextPoint;
	//增量计算
	iIncpid = sptr->Proportion * iError //E[k]项
	- sptr->Integral * sptr->LastError //E[k－1]项
	+ sptr->Derivative * sptr->PrevError; //E[k－2]项
	//存储误差，用于下次计算
	sptr->PrevError = sptr->LastError;
	sptr->LastError = iError;
	//返回增量值
	iIncpid /= 2000;
	return(iIncpid);
}
